<template>
	<view class="content">
		<cu-custom bgColor="" :isBack="true" textRight="false" type="1">
			<block slot="backText" class="titilestyle">{{title}}</block>

		</cu-custom>


		<scroll-view scroll-y="true" class="padding-lr margin-top" :style="{height:scrollH+'px'}" v-if="good">
			<view>
				<swiper class="swiper-box" indicator-active-color="#FFFFFF" :indicator-dots="true" :autoplay="true"
					:interval="3000" :duration="1000">
					<swiper-item v-for="(item,index) in good.goods_thumbs" :key="index">
						<view class="swiper-item  border-radius ">
							<image :src="item" mode="widthFix"></image>

						</view>
					</swiper-item>

				</swiper>
			</view>
			<view class="bg-white padding border-radius margin-top">
				<text class="text-bold text-xl">{{good.goods_name}}</text>
				<view class="margin-top" v-if="good.intro">
					{{good.intro}}
				</view>
				<view class="margin-top">
					<text class="text-price text-xl text-red text-bold">{{good.price*good.discount}}</text>
					<text class=" text-gray  margin-left-sm s-pass-price" v-if="good.discount<1">{{good.price}}</text>
					<text class="cu-tag1 bg-red margin-left-sm" v-if="good.discount<1">{{good.discount*10}}折</text>

				</view>
				<view class="flex justify-between margin-top-sm text-gray">
					<view class="">
						销量：{{good.sold_num}}
					</view>
					<view class="" v-if="good.is_stock==1">
						库存：{{good.stock_num}}
					</view>

				</view>
			</view>
			<view class="bg-white  margin-top border-radius spec-box" v-if="good.spec.length>0">
				<view v-for="(spec,index) in specGoods.spec" :key="index">
					<text class="spec_name">{{spec.spec_name}}</text>
					<view class="flex margin-top-sm">
						<view class="spec-item middle" v-for="(itemvalue,keys) in spec.items" :key="keys"
							:class="[itemvalue.checked==1?'hov':'no-hover']" :data-index="index" :data-key="keys"
							@click="checkItem">
							{{itemvalue.item_name}}
						</view>
					</view>
				</view>
			</view>

			<view class="margin-top ">
				<wxParse :content="good.content"></wxParse>
			</view>

			<view class="foot">

			</view>
		</scroll-view>

		<view class="bg-white padding flex justify-between align-center  bottom">
			<view class="flex align-center text-xl  text-bold ">
				<text class="padding-right-sm">数量:</text>
				<yp-number-box class="middle text-xl" :min="0" :max="10" :value="total" :index="good.goods_id"
					@change="cart">
				</yp-number-box>

			</view>
			<view class="cu-btn bg-blue border-radius" @click="addCart()">
				加入购物车
			</view>
			<view class="cu-btn bg-blue border-radius" @click="subOrder()">
				立即下单
			</view>
		</view>

	</view>
</template>

<script>
	import wxParse from "@/components/gaoyia-parse/parse.vue"
	import ypNumberBox from "@/app/ShopCenter/components/yp-number-box/yp-number-box.vue";
	export default {
		components: {
			ypNumberBox,
			wxParse
		},
		data() {
			return {
				scrollH: this.WH - this.CustomBar-55,
				good: null,
				specGoods: {}, //选择的规格
				shop_id: -1,
				status: -1,
				user_id: 0,
				domain: this.resDomain,
				isLoading: false, //是否加载完成显示
				loadStatus: 'load',
				StatusBar: this.Custom,
				shop_id: 0,
				is_change: false,
				specGoods: {}, //规格
				checkedItems: {},
				checkedNum: 0,
				checkedPrice: 0,
				itemPrice: {},
				cartList: null,
				cartInfo: {
					'total_goods_price': 0,
					'goodsList': {}
				},
				singleCart: [], //一次性购物列表
				total: 1,

			}
		},
		onLoad(option) {
			this.status = option.status;
			this.shop_id = option.shop_id;
			uni.getStorage({
				key: "good",
				success: (r) => {

					this.good = r.data;
					this.selectSpec();
				}
			})
			this.apiRequest('/buyer/userInfo', {
				area_id: uni.getStorageSync('area_id'),
			}).then(res => {
				this.userInfo = res.data
				this.user_id = this.userInfo.user_id;
			})

		},
		onShow() {
			/**
			 * 获取本地购物车的数据
			 */
			const res = uni.getStorageSync('cartList-' + this.shop_id);
			if (res) {
				this.cartList = res
			} else {
				this.cartList = {}
			}
			const res1 = uni.getStorageSync('cartInfo-' + this.shop_id);
			if (res1) {
				this.cartInfo = res1
			} else {
				this.$set(this.cartInfo, 'total_goods_price', 0)
				this.$set(this.cartInfo, 'goodsList', {})
				this.$set(this.cartInfo, 'total_num', 0)
				this.$set(this.cartInfo, 'goods_real_price', 0)
			}


			const res2 = uni.getStorageSync('cartGoodsNum-' + this.shop_id);
			if (res2) {
				this.cartGoodsNum = res2
			} else {
				this.cartGoodsNum = {}
			}


			console.log(this.cartList);

		},

		methods: {


			/**
			 * 加载规格
			 * @param {Object} 
			 */
			selectSpec() {
				this.is_change = false;
				this.specGoods = this.good;
				this.checkedItems = {}
				this.checkedPrice = 0
				this.checkedNum = 0
				var that = this
				var cGoods = {};

				this.specGoods['spec'].forEach(function(spec, index) {
					spec['items'].forEach(function(item, key) {
						that.itemPrice[item['item_id']] = parseFloat(item['price'])
						item['checked'] = 0;
						if (Object.keys(cGoods).length > 0) {
							if (cGoods.item.indexOf(item['item_id']) != -1) {
								item['checked'] = 1;
								that.checkedNum = cGoods.num;
								that.checkedItems[item['item_id']] = item['item_name']
								that.checkedPrice += parseFloat(item['price'])
							}
						} else {
							if (key == 0) {
								item['checked'] = 1;
								(spec['select_type'] == 1) ? (() => {
									item['checked'] = 0;

									delete(that.checkedItems[item['item_id']])
								})() : (() => {
									that.checkedItems[item['item_id']] = item['item_name'];
									that.checkedPrice += parseFloat(item['price'])
								})();
							}
						}
					})
				});


				console.log(this.specGoods['spec'][0]);

			},
			/**
			 * 选择规格
			 * @param {Object} e
			 */
			checkItem(e) {
				this.is_change = false
				var that = this
				this.checkedNum = 0
				this.checkedPrice = parseFloat(this.specGoods.price)
				this.specGoods.spec[e.target.dataset.index]['items'].forEach(function(item, key) {
					if (that.specGoods.spec[e.target.dataset.index].select_type == 0) { //处理单选
						if (key == e.target.dataset.key) {
							item['checked'] = 1;
							that.checkedItems[item['item_id']] = item['item_name']
						} else {
							item['checked'] = 0;
							delete(that.checkedItems[item['item_id']])
						}
					} else { //处理多选
						if (key == e.target.dataset.key) {
							if (item['checked'] == 1) {
								item['checked'] = 0
								delete(that.checkedItems[item['item_id']])
							} else {
								item['checked'] = 1
								that.checkedItems[item['item_id']] = item['item_name']
							}
						}
					}
				})
				var nowItem = '' //当前选中的规格
				for (var item in this.checkedItems) {
					nowItem += item + ','
					that.checkedPrice += parseFloat(that.itemPrice[item])
				}

				if (nowItem) {
					nowItem = nowItem.substr(0, nowItem.length - 1)
				}

				if (Object.keys(this.cartList).length > 0) {
					for (var cartItem in this.cartList) {
						if (this.cartList[cartItem].goods_id == that.specGoods.goods_id && this.cartList[cartItem].item ==
							nowItem) {
							this.checkedNum = this.cartList[cartItem].num
						}
					}
				}
			},

			/**
			 * 添加购买数量
			 * @param {Object} e
			 */
			cart(e) {

				var items = '';
				var cart = {};
				if (e.item != null) {
					items = e.item
				} else {
					if (Object.keys(this.checkedItems).length > 0 && this.specGoods.goods_id == this.good.goods_id) {
						let i = 0
						for (var item in this.checkedItems) {
							if (i == 0) {
								items += item
							} else {
								items += ',' + item
							}
							i++
						}
					}
				}
				this.total = e.num;
				this.$set(cart, 'goods_id', this.good.goods_id);
				this.$set(cart, 'num', e.num);
				this.$set(cart, 'item', items);
				var that = this;
				var is_do = 0 //本次商品是否处理
				for (var cartItem in this.cartList) {
					if (cart.goods_id == that.cartList[cartItem].goods_id && that.cartList[cartItem].item ==
						items) { //查找商品是否存在购物车
						if (cart.num > 0) {
							this.$set(this.cartList, cartItem, cart)
						} else {
							delete(that.cartList[cartItem])
							this.checkedNum = 0
						}
						is_do = 1
					}
				}
				if (is_do == 0 && cart.num > 0) { //如果本次没处理，说明是新数据，追加到购物车中
					this.$set(this.cartList, cart.goods_id + '-' + cart.item, cart)
				}
				let num = 0
				if (Object.keys(this.cartList).length > 0) {
					for (var cartKey in this.cartList) {
						if (this.cartList[cartKey].goods_id == cart.goods_id) {
							num += parseFloat(this.cartList[cartKey].num)
						}
					}
					this.$set(this.cartGoodsNum, cart.goods_id, parseFloat(num))
				} else {
					this.cartInfo = {
						'total_goods_price': 0,
						'goodsList': {}
					}
					this.cartGoodsNum = {}
					uni.removeStorageSync('cartList-' + this.shop_id);
					uni.removeStorageSync('cartInfo-' + this.shop_id);
					return
				}

			},
			/**
			 * 添加至购物车
			 */
			addCart() {


				if (this.status == 0) {
					uni.showToast({
						title: '暂停营业',
						duration: 1000,
						icon: 'none'
					});
					return;
				}


				let isset = -1;
				for (let i in this.cartList) {
					let id = this.good.goods_id + "-";
					 isset = i.indexOf(id);
					if (isset != -1) {
						break;
					}
				}
				if (isset == -1) {
					let a = {
						'index': this.good.goods_id,
						'num': 1,
						'item': null
					}
					this.cart(a);
				}

				uni.setStorageSync('cartGoodsNum-' + this.shop_id, this.cartGoodsNum);
				uni.setStorageSync('cartList-' + this.shop_id, this.cartList);
				this.apiRequest('/buyer/addCart', {
					cartList: this.cartList,
					shop_id: this.shop_id,
					user_id: this.user_id
				}).then(res => {
					
					if (res.code != 200) {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
						return
					}else{
						uni.showToast({
							title: "加入成功",
							icon: "none"
						})
					}

					this.cartInfo = res.data;
					uni.setStorageSync('cartInfo-' + this.shop_id, this.cartInfo);

					setTimeout(() => {
						uni.navigateBack({
							delta: 1,
						})
					}, 1000)

				})


			},

			/**
			 * 去结算
			 */
			subOrder() { //去结算
				if (this.status == 0) {
					uni.showToast({
						title: '暂停营业',
						duration: 1000,
						icon: 'none'
					});
					return;
				}
				//默认

				let isset = -1;
				for (let i in this.cartList) {
					let id = this.good.goods_id + "-";
					 isset = i.indexOf(id);
					if (isset != -1) {
						this.singleCart[0] = this.cartList[i];
						break;
					}
				}
				if (isset == -1) {
					let a = {
						'index': this.good.goods_id,
						'num': 1,
						'item': null
					}
					this.cart(a);
					for (let k in this.cartList) {
						let idd = this.good.goods_id + "-";
						let isset = k.indexOf(idd);
						if (isset > -1) {
							this.singleCart[0] = this.cartList[k];
							break;
						}
					}
				}


				this.apiRequest('/buyer/userInfo', {
					area_id: uni.getStorageSync('area_id')
				}, 1).then(r => {
					if (r.code == 200) {
						this.apiRequest('/buyer/addCart', {
							cartList: this.singleCart,
							shop_id: this.shop_id,
							user_id: this.user_id
						}, 1).then(res => {
							if (res.code == 200) {

								uni.setStorageSync('cartList-' + this.shop_id + "-" + this.good.goods_id,
									this.singleCart);
								this.cartInfo = res.data
								uni.setStorageSync('cartInfo-' + this.shop_id + '-' + this.good.goods_id,
									this.cartInfo)
								uni.navigateTo({
									url: '/app/ShopCenter/pages/orderSub?shop_id=' + this.shop_id +
										"&good_id=-" + this.good.goods_id
								});
							}
						})
					}
				})

			},
		}

	}
</script>

<style>
	.cu-tag1 {
		padding-left: 10rpx;
		padding-right: 10rpx;
		border-radius: 5rpx;
		margin-left: 10rpx;
	}

	.s-pass-price {
		text-decoration: line-through;
	}

	.spec-box {
		padding-bottom: calc(100vw*(60/750));
		padding-top: calc(100vw*(60/750));
		padding-left: calc(100vw*(40/750));
		padding-right: calc(100vw*(40/750));
	}

	.border-radius {
		border-radius: 12rpx;
	}

	.bottom {
		width: 100vw;
		position: absolute;
		z-index: 99;
		bottom: 0;
	}

	.swiper-box {
		height: calc(100vw*(702/750));
	}

	.swiper-item {
		width: 100%;
		height: calc(100vw*(702/750));
		background-position: center;
		background-size: cover;
		background-repeat: no-repeat;
		border-radius: 12rpx;

	}
	.swiper-item image{
		width: 100%;
		border-radius: 12rpx;
		max-height: calc(100vw*(702/750));
	}

	.spec_name {
		font-size: calc(100vw*(24/750));
		font-family: PingFang SC;
		font-weight: 500;
		color: #999999;
	}

	.spec-item {
		min-width: calc(100vw*(148/750));
		height: calc(100vw*(60/750));
		border-radius: calc(100vw*(10/750));
		margin-right: calc(100vw*(10/750));
	}

	.no-hover {
		background: #F7F7F7;
		font-size: calc(100vw*(24/750));
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
	}

	.hov {
		background: #1270E0;

		font-size: calc(100vw*(24/750));
		font-family: PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
	}

</style>
